package com.xsprite.managesys.servlet.gm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.mina.core.session.IoSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.game.GMClientServer;
import com.game.gm.config.GMComm;
import com.game.gm.handler.ResLoadServersTableGMHandler;
import com.game.gm.load.GMCommLoad;
import com.game.gm.manager.GMManager;
import com.xsprite.managesys.servlet.BaseServlet;

/**
 * Servlet implementation class LoadServersTableServlet
 */
public class LoadServersTableServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    private List<ResLoadServersTableGMHandler> handlers = new ArrayList<ResLoadServersTableGMHandler>();
	private long firstCheckTime = 0L;
    
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		try {
			com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(queryParam("paras"));
			if (checkParas(jsonObj)) {
				loadServersTable(jsonObj);
				firstCheckTime = System.currentTimeMillis();
				while (!isHandlersFinished()) {
					Thread.sleep(500);
				}
				getResp().getWriter().print(makeResult());
			}
		} catch (Exception ex) {
			getResp().getWriter().print(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	private String makeResult(){
		StringBuffer result = new StringBuffer();
		for(ResLoadServersTableGMHandler handler : handlers){
			result.append(handler.getResultInfo());
		}
		handlers.clear();
		return result.toString();
	}
	
	private boolean isHandlersFinished(){
		long now = System.currentTimeMillis();
		if((now - firstCheckTime) > (10 * 1000)){
			return true;
		}
		for(ResLoadServersTableGMHandler handler : handlers){
			if(!handler.isFinish()){
				return false;
			}
		}
		return true;
	}

	private void loadServersTable(JSONObject jsonObject) throws IOException{
		String command = makeCommand(jsonObject);
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		
		for(int i = 0; i < serversArray.size(); i++){
			JSONObject serverObj = (JSONObject) serversArray.get(i);
			String tag = serverObj.getString("tag");
			ResLoadServersTableGMHandler handler = new ResLoadServersTableGMHandler();
			handler.setAttachInfo("serverId = " + tag);
			handler.setUserid(getReq().getSession().getAttribute("userid").toString());
			handler.setGmNo(10);
			handlers.add(handler);
			IoSession session = GMClientServer.getInstance().createSession(tag, getResp().getWriter(), handler);
			GMManager.getInstance().sendGMmsg(session, command);
		}
	}

	private String makeCommand(JSONObject jsonObject) {
		GMComm comm = (GMComm) GMCommLoad.getInstance().getGmComms().get(Integer.valueOf(10));
		String redataName = jsonObject.getString("redataName");
		StringBuffer sendBuf = new StringBuffer();
		sendBuf.append(comm.getGmComm());
		sendBuf.append(" ");
		sendBuf.append(redataName);
		return sendBuf.toString();
	}

	private boolean checkParas(JSONObject jsonObject) throws IOException {
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		if (serversArray.size() < 1) {
			getResp().getWriter().print("服务器不能为空");
			return false;
		}
		String redataName = jsonObject.getString("redataName");
		if (redataName == null || redataName.equals("")) {
			getResp().getWriter().print("表名不能为空");
			return false;
		}
		return true;
	}
}
